import { getLunarDay } from '../../utils/util'
const appData = getApp().globalData
Component({
    data: {
        // 这里是一些组件内部数据
        someData: {},
        weekList: ['日', '一', '二', '三', '四', '五', '六'],
        dateList: [],
        currentDate: [],
        height: appData.height,
        lunarDay: getLunarDay()
    },
    methods: {
        initDate () {
            const now = new Date()
            const year = now.getFullYear()
            const month = now.getMonth()
            const day = now.getDate()
            const week = now.getDay()
            this.setData({
                currentDate: [year, month + 1, day, week]
            })
            this.initDateList()
        },
        initDateList() {
            const firstDayWeek = this.getFirstWeek()
            // 从第几位开始
            const first = firstDayWeek === 7 ? 0 : firstDayWeek
            const days = this.getDaysThisMonth()
            let i = 0
            let count = 0
            const dateList = []
            while(count < days) {
                if (i >= first) {
                    count++
                    dateList.push({
                        date: count,
                        isCurrentDay: count === this.data.currentDate[2]
                    })
                } else {
                    dateList.push({
                        date: '',
                        isCurrentDay: false
                    })
                }
                i++
            }
            this.setData({
                dateList
            })
        },
        // 计算当月第一天是周几
        getFirstWeek() {
            const current = this.data.currentDate
            return new Date(`${current[0]}/${current[1]}/${current[2]}`).getDay()
        },
        // 计算当月有几天
        getDaysThisMonth() {
            const current = this.data.currentDate
            let days = 0
            if ([1, 3, 5, 7, 8, 10, 12].includes(current[1])) {
                days = 31
            } else if ([4, 6, 9, 11].includes(current[1])) {
                days = 30
            } else {
                if (this.isLeapYear()) {
                    days = 29
                } else {
                    days = 28
                }
            }
            return days
        },
        // 是否是闰年
        isLeapYear() {
            const year = this.data.currentDate[0]
            // 闰年公式：1. 是4的倍数且不是100的倍数 2.是400的倍数 两者满足其一即为闰年
            return year % 4 === 0 && year % 100 !== 0 || year % 400 == 0
        }
    },
    lifetimes: {
        attached() {
            this.initDate()
        }
    },
    attached() {
        this.initDate()
    }
})